package com.second.app.util;

import com.second.app.enums.CommonCodeEnum;
import com.second.app.exception.MyException;
import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;


import java.util.Date;
import java.util.HashMap;

/**
 * @author gyz
 * @date 2020/12/26 10:48
 */
public class JwtUtils {
    public static final String SUBJECT = "admin";
    static final long EXPIRATION_TIME = 60 * 60 * 1000;
    static final String APP_SECRET = "second_jwt_secret";


    /**
     * 生成token
     *
     * @param userNo
     * @return
     */
    public static String generateToken(String userNo) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userNo", userNo);

        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("id", userNo)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, APP_SECRET).compact();

        return token;
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */

    public static Boolean validateToken(String token) {

        if (StringUtils.isEmpty(token)) {
            throw new MyException(CommonCodeEnum.ERROR, "未检测到token");
        }
        try {
            Claims claims = Jwts.parser().setSigningKey(APP_SECRET).
                    parseClaimsJws(token).getBody();
            if (StringUtils.isNotEmpty(claims.getId())) {
                return true;
            }
        } catch (ExpiredJwtException e) {
            throw new MyException(CommonCodeEnum.ERROR, "token失效");
        } catch (UnsupportedJwtException e) {
            throw new MyException(CommonCodeEnum.ERROR, "token验证失败");
        } catch (MalformedJwtException e) {
            throw new MyException(CommonCodeEnum.ERROR, "token验证失败");
        } catch (SignatureException e) {
            throw new MyException(CommonCodeEnum.ERROR, "token验证失败");
        } catch (IllegalArgumentException e) {
            throw new MyException(CommonCodeEnum.ERROR, "token验证失败");
        }

        return null;

    }


}
